public class SnakeFood extends SnakePixel {

    private SnakeBody body = null;
    private SnakeHead head = null;
    private Canvas canvas = null;

    public SnakeFood() {}

    public SnakeFood(SnakeBody body) {
        this(SnakeColor.rand(), 'F', body);
    }

    public SnakeFood(int color, char ch, SnakeBody body) {
        set(color, ch, body);
    }

    public SnakeFood set(int color, char ch, SnakeBody body) {
        this.color = color;
        this.ch = ch;
        this.body = body;
        head = body.head;
        canvas = head.canvas;
        rand();

        return this;
    }

    //检测食物随机坐标是否合法(不能随机到蛇头和蛇身上)
    public boolean check(int x, int y) {
        if (x == head.x && y == head.y)
            return false;

        Pos t;
        while (body.next()) {
            t = body.value();
            if (x == t.x && y == t.y) {
                return false;
            }
        }
        return true;
    }

    // 新食物随机坐标
    public SnakeFood rand() {
        int x, y;

        while (true) {
            x = Kyo.rand(1, canvas.h() - 2);
            y = Kyo.rand(1, canvas.w() - 2);
            if (check(x, y))
                break;
        }
        this.set(x, y, SnakeColor.rand(), ch);

        return this;
    }
}
